// 引用封装好的auth中间件
const authMiddleware = require('../middlewares/auth')
// 引入express模块
const express = require('express')
// const multer = require('multer')
// const path = require('path')
// 引入用户控制器
const UserController = require('../controllers/users')
const Users = require('../models/users')
// 创建路由
const router = express.Router()
const upload = require('../utils/upload')

// 图片上传接口
router.post(
  '/upload',
  upload.single('avatar'),
  authMiddleware,
  async (req, res) => {
    const file = req.file

    if (!file) {
      return res.status(400).send('No file uploaded.')
    }

    if (!req.file) {
      return res.status(400).send({
        code: 0,
        msg: 'No file uploaded.'
      })
    }
    // 获取上传的文件信息
    const fileId = req.file.id
    const fileName = 'http://localhost:3000/uploads/' + req.file.filename
    const userId = req.user.userId // 这里应该是用户的MongoDB _id

    try {
      const updatedUser = await Users.findByIdAndUpdate(
        userId,
        { avatar: fileName },
        { new: true }
      )
      if (!updatedUser) {
        return res.status(404).send('User not found.')
      }
      res.send({
        code: 200,
        msg: 'File uploaded successfully.',
        data: {
          fileId: fileId,
          fileName: fileName
        }
      })
    } catch (err) {
      console.error('Error updating user:', err)
      res.status(500).send('Error updating user.')
    }
  }
)

// 注册用户接口
router.post('/register', UserController.register)

// 登录接口
router.post('/login', UserController.login)

// 获取所有用户
router.get('/users', authMiddleware, UserController.getUsers)

// 获取单个用户
router.get('/users/:id', authMiddleware, UserController.getUsersById)

// 更新用户信息
router.put('/users/:id', authMiddleware, UserController.updateUsers)

// 删除用户
router.delete('/users/:id', authMiddleware, UserController.deleteUsers)

module.exports = router
